home *** CD-ROM | disk | FTP | other *** search
- Path: quasar.engr.sgi.com!davea
- From: davea@quasar.engr.sgi.com (David B.Anderson)
- Newsgroups: comp.lang.c
- Subject: Re: Checking to See if a File Exists
- Date: 28 Jan 1996 18:47:50 GMT
- Organization: Silicon Graphics, Inc., Mountain View, CA
- Message-ID: <4eggcm$o0j@fido.asd.sgi.com>
- References: <DLtI7G.HpE@midway.uchicago.edu> <9601281412.AA0001c@doodey.demon.co.uk>
- NNTP-Posting-Host: quasar.engr.sgi.com
-
- In article <9601281412.AA0001c@doodey.demon.co.uk>,
- Paul F. Robinson <pfr@doodey.demon.co.uk> wrote:
- >josef jurek (jaj3@kimbark.uchicago.edu) wrote:
- >:
- >: How does one check from a C program to see whether a file
- >: exists or not?
- >
- >Your compiler library might have an access() function.
-
- Be careful: on UN*X systems, access() uses different file
- permissions checks than open()(or fopen()) to deterimine if
- you are allowed to get at the file.
-
- And indeed neither open() nor fopen() nor access() prove the
- file does not exist when they fail. All it proves is that you
- cannot open(), fopen() or access() the file.
-
- Of course on machines and/or file systems without any notion of
- file permissions any of them you have available may do what you want.
-
- >Alternatively,
- >attempt to open the file with fopen().
- >If successful, the file exists. -Don't forget to fclose() it.
- >If unsuccessful, check the value of errno. ENOENT (from errno.h)
- > indicates that the file does not exist.
-
- fopen() is not guaranteed by ISO C to set errno at all. If you
- are dealing with XPG4-compliant systems, you do get a
- stronger guarantee: xpg4 does guarantee errno is set. Cautious
- folks will set errno to 0 before calling fopen() so if it
- *fails* to set errno you can tell it failed to do so.
-
- I don't have the POSIX doc here at home, but do have XPG4 doc
- available, so I checked that... and ISO C.
-
- A better choice than fopen()/open()/access() would be one of
- the 'stat' functions, such as stat() (or lstat()). Because
- they will not fail due to lack of permission on the file. If
- you have them available.
-
- What you use will depend on what you are going to do with the
- information that the file exists. You should consider putting
- the code into a separate function and documenting the function
- as being a potential portability problem.
-
- Regards,
- [ David B. Anderson (415)933-4263 davea@sgi.com ]
- [ Suddenly to me that no verb in this sentence. -m.toy]
-